<template>
    <el-card class="w-full pt-[5px]">
        <el-radio-group v-model="planType" @change="getList(1)">
            <el-radio-button v-for="item in statisticsList" :key="item.value" :value="item.value">{{ item.name }}({{
            item.count
        }})</el-radio-button>
        </el-radio-group>
        <el-form :model="searchForm" class="mt-[20px]" label-width="110px">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="申报计划名称" class="mb-[0px]">
                        <el-input v-model="searchForm.name" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="奖励名称" class="mb-[0px]">
                        <el-input v-model="searchForm.honorName" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="" label-width="0" class="mb-[0px]">
                        <CommonDateSelect placeholder="申报开始日期" v-model:beginTime="searchForm.beginDateStart"
                            v-model:endTime="searchForm.beginDateEnd" v-model:dateformat="searchForm.beginDateFormat" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <div class="flex justify-end">
                        <el-button type="primary" @click="searchFormOpen = !searchFormOpen">更多
                            <el-icon color="#fff">
                                <CaretTop v-show="searchFormOpen" />
                                <CaretBottom v-show="!searchFormOpen" />
                            </el-icon>
                        </el-button>
                        <el-button type="primary" @click="queryMet">查询</el-button>
                        <el-button @click="reset">重置</el-button>
                    </div>
                </el-col>
            </el-row>
            <el-row :gutter="20" class="mt-[20px]" v-show="searchFormOpen">
                <el-col :span="12">
                    <el-form-item label="" label-width="0">
                        <CommonDateSelect placeholder="申报结束日期" v-model:beginTime="searchForm.endDateStart"
                            v-model:endTime="searchForm.endDateEnd" v-model:dateformat="searchForm.endDateFormat" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="奖励级别" class="mb-[0px]">
                        <!-- <el-select v-model="searchForm.honorLevel">
                            <el-option v-for="item in hjjbList" :key="item.code" :label="item.name"
                                :value="item.code" />
                        </el-select> -->
                        <CustomTreeSelect placeholder="奖励级别" v-model="searchForm.honorLevel" valueKey="code"
                            labelKey="name" :isFetch="false" :dataList="hjjbList" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="自动截至" class="mb-[0px]">
                        <el-select v-model="searchForm.isAutoEnd" clearable>
                            <el-option label="是" value="1" />
                            <el-option label="否" value="0" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="可转入评审" class="mb-[0px]">
                        <el-select v-model="searchForm.isReview" clearable>
                            <el-option label="是" value="1" />
                            <el-option label="否" value="0" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="申报状态" class="mb-[0px]">
                        <!-- <el-select v-model="searchForm.applyState">
                            <el-option v-for="item in sbztList" :key="item.code" :label="item.name"
                                :value="item.code" />
                        </el-select> -->
                        <CustomTreeSelect placeholder="申报状态" v-model="searchForm.applyState" valueKey="code"
                            labelKey="name" :isFetch="false" :dataList="sbztList" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </el-card>
    <el-card class="w-full pt-[5px] mt-[10px]">
        <div class="mb-[20px]">
            <el-button type="primary" v-equalRole="['biz_kycgly']" @click="handleAdd">
                <el-icon class="mr-[5px]">
                    <Plus />
                </el-icon>
                新增
            </el-button>
            <el-button v-equalRole="['biz_kycgly', 'biz_kyms']" @click="handleDel">
                <el-icon>
                    <DeleteFilled />
                </el-icon>
                删除
            </el-button>
            <el-button @click="historyVisible = true">
                历史申报
            </el-button>
        </div>
        <el-table :data="tableData" class="w-full" @selection-change="handleSelectionChange" stripe>
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="申报计划名称">
                <template #default="scope">
                    <el-link type="primary" @click="viewItem(scope.row)">{{ scope.row.name }}</el-link>
                </template>
            </el-table-column>
            <el-table-column prop="honorName" label="奖励名称" />
            <el-table-column prop="beginDate" label="申报开始时间" />
            <el-table-column prop="endDate" label="申报结束时间" />
            <el-table-column prop="applyState" label="申报状态">
                <template #default="scope">
                    <Feedback :id="scope.row.applyState" :list="sbztList">
                    </Feedback>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="360" align="center">
                <template #default="scope">
                    <el-button type="primary" v-equalRole="['biz_kycgly']" size="small" plain
                        @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button type="primary" v-equalRole="['biz_kycgly']"
                        v-show="scope.row.applyState == '0' || scope.row.applyState == '2'" size="small" plain
                        @click="start(scope.row, '1')">
                        启动
                    </el-button>
                    <el-button type="primary" v-equalRole="['biz_kycgly']" v-show="scope.row.applyState == '1'"
                        size="small" plain @click="start(scope.row, '2')">
                        结束
                    </el-button>
                    <el-button type="primary" size="small"
                        v-show="scope.row.applyState == '1' || scope.row.applyState == '2'" plain
                        @click="goSbcl(scope.row)">
                        查看申报
                    </el-button>
                    <el-button type="primary" size="small" v-equalRole="['biz_kycgly']" plain
                        v-show="scope.row.isCompleteChangeReview == '0' && scope.row.applyState == '2'"
                        @click="handlepsAdd(scope.row)">
                        转入评审
                    </el-button>
                    <el-button type="primary" size="small" plain @click="delHonor(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="mt-[20px] flex justify-end">
            <pagination v-show="total > 0" :total="total" v-model:page="pageInfo.pageNum"
                v-model:limit="pageInfo.pageSize" @pagination="getList" />
        </div>
    </el-card>
    <EditModal v-model="editModelVisible" ref="EditModalRef" :hjjbList="hjjbList" @callBack="callBackFun" />
    <psEditModal v-model="pseditModelVisible" ref="psEditModalRef" :fatableData="fatableData" :infoObj="infoObj"
        @callBack="callBackFun" />
    <viewModal v-model="ViewdialogVisible" ref="viewModalRef" :hjjbList="hjjbList" />
    <historyModal v-model="historyVisible" />
</template>

<script setup>
import useOperate from "@/hooks/operate";
import { onMounted } from "vue";
import { getCategory } from "@/api/system/category";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
    gethonorApplyList,
    honorApplyDel,
    gethonorApplyInfo,
    getreviewSchemeList,
    updateStatusById,
    gethonorApplyListStatistics
} from "@/api/achievement/cghj";
import EditModal from "./EditModal.vue";
import psEditModal from "./psEditModal.vue";
import viewModal from "./viewModal.vue";
import useCategoryStore from "@/store/modules/category";
import CustomTreeSelect from "@/views/project/components/CustomTreeSelect.vue";
import CommonDateSelect from "@/views/achievement/components/CommonDateSelect";
import historyModal from "./historyModal.vue";
import Cookies from 'js-cookie'


const categoryStore = useCategoryStore();
const { sbztList, hjjbList } = storeToRefs(categoryStore); // 解构状态
const { getsbztList, gethjjbList } = categoryStore; // 解构方法

const router = useRouter();
const planType = ref("");
const searchFormOpen = ref(false);
const editModelVisible = ref(false);
const pseditModelVisible = ref(false);
const ViewdialogVisible = ref(false);
const historyVisible = ref(false);


const searchForm = ref({
    name: "",
    honorName: "",
    beginDateStart: "",
    beginDateEnd: "",
    beginDateFormat: "yyyy-MM-dd",
    endDateStart: "",
    endDateEnd: "",
    endDateFormat: "yyyy-MM-dd",
    honorLevel: [],
    isAutoEnd: "",
    isReview: "",
    applyState: [],
});
const pageInfo = ref({
    pageNum: 1,
    pageSize: 10,
});
const total = ref(0);
const tableData = ref([]);
//点击新增
const handleAdd = () => {
    editModelVisible.value = true;
};
const infoObj = ref({
    name: "",
    id: "",
});
//点击新增
const handlepsAdd = (i) => {
    infoObj.value.name = i.name;
    infoObj.value.id = i.id;
    pseditModelVisible.value = true;
};
const EditModalRef = ref(null);
//点击编辑
const handleEdit = (i) => {
    gethonorApplyInfo(i.id).then((res) => {
        if (res.code == 200) {
            editModelVisible.value = true;
            EditModalRef.value.getRuleForm(res.data);
        }
    });
};
const psEditModalRef = ref(null);
const fatableData = ref([]);
const getfaList = async () => {
    let parms = {
        pageNum: 1,
        pageSize: 100,
    };
    let res = await getreviewSchemeList(parms);
    if (res.code == 200) {
        fatableData.value = res.rows;
    }
};
const goSbcl = (i) => {
    router.push({
        path: "/achievement/cghj/sbhj/detail",
        query: { id: i.id, honorName: i.honorName, honorLevel: i.honorLevel, isReview: i.isReview },
    });
};

const viewModalRef = ref(null);
const viewItem = (i) => {
    gethonorApplyInfo(i.id).then((res) => {
        if (res.code == 200) {
            ViewdialogVisible.value = true;
            viewModalRef.value.getRuleForm(res.data);
        }
    });
};
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
};
//点击删除
const handleDel = () => {
    if (multipleSelection.value.length == 0) {
        ElMessage.warning("请选择要删除的数据");
        return;
    } else {
        ElMessageBox.confirm("是否确认删除？", "提示", {
            type: "warning",
        }).then(() => {
            let ids = multipleSelection.value.map((item) => item.id);
            ids = ids.join(",");
            honorApplyDel(ids).then((res) => {
                if (res.code == 200) {
                    getList();
                    ElMessage.success("删除成功");
                }
            });
        });
    }
};

const initList = () => {
    getList();
};

const reset = () => {
    searchForm.value = {
        name: "",
        honorName: "",
        beginDateStart: "",
        beginDateEnd: "",
        beginDateFormat: "yyyy-MM-dd",
        endDateStart: "",
        endDateEnd: "",
        endDateFormat: "yyyy-MM-dd",
        honorLevel: [],
        isAutoEnd: "",
        isReview: "",
        applyState: [],
    };
};
const getList = async (i) => {
    gethonorApplyListStatisticsList()
    if (i == 1) {
        pageInfo.value.pageNum = 1;
    }
    let parms = {
        ...searchForm.value,
        ...pageInfo.value,
        applyStateGroup: planType.value,
    };
    parms.honorLevel = searchForm.value.honorLevel.join(",");
    parms.applyState = searchForm.value.applyState.join(",");
    let res = await gethonorApplyList(parms);
    if (res.code == 200) {
        tableData.value = res.rows;
        total.value = res.total;
    }
};

const statisticsList = ref([{
    name: "全部",
    value: '',
    count: 0
},
{
    name: "未启动",
    value: '0',
    count: 0
},
{
    name: "申报中",
    value: '1',
    count: 0
},
{
    name: "已停止",
    value: '2',
    count: 0
}])

const gethonorApplyListStatisticsList = async () => {
    let parms = {
        ...searchForm.value,
    };
    parms.honorLevel = searchForm.value.honorLevel.join(",");
    parms.applyState = searchForm.value.applyState.join(",");
    let res = await gethonorApplyListStatistics(parms);
    if (res.code == 200) {
        statisticsList.value.forEach(item => {
            if (item.name != '全部') {
                let hasStatis = res.data.filter(item1 => {
                    return item1.applyState == item.value
                })
                console.log(hasStatis);
                hasStatis && hasStatis.length ? item.count = hasStatis[0].count : item.count = 0
            }


        })
        let allNum = 0
        res.data.forEach(item => {
            allNum += item.count
        })
        statisticsList.value[0].count = allNum
    }
};
const callBackFun = (i) => {
    getList();
};
const delHonor = (i) => {
    ElMessageBox.confirm("确认！删除这条数据?", "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            honorApplyDel(i.id).then((res) => {
                if (res.code == 200) {
                    getList();
                    ElMessage.success("删除成功");
                }
            });
        })
        .catch(() => { });
};

const checkIfExpired = (i) => {
    const today = new Date(); // 获取今天的日期和时间
    const targetDate = new Date(i); // 解析指定日期字符串为Date对象
    targetDate.setHours(0, 0, 0, 0); // 将时间设置为0，只比较日期部分
    today.setHours(0, 0, 0, 0); // 将今天的时间也设置为0，只比较日期部分

    return targetDate < today; // 比较两个日期，判断是否过期
}

const start = (i, j) => {
    if (j == '1') {
        console.log(i)
        console.log(checkIfExpired(i.endDate))
        if (checkIfExpired(i.endDate)) {
            ElMessage.warning(`申报计划已经在${i.endDate}结束申请，若需重新启动请先修改申请结束日期`);
            return
        }
    }
    updateStatusById({
        id: i.id,
        applyState: j,
    }).then((res) => {
        if (res.code == 200) {
            getList();
        }
    });
};

const queryMet = () => {
    getList(1)
}

onMounted(() => {
    if (!sbztList.value.length) {
        getsbztList();
    }
    if (!hjjbList.value.length) {
        gethjjbList();
    }
    initList();
    if (Cookies.get("role-key") == 'biz_kycgly') {
        getfaList();
    }

});
</script>

<style scoped lang="scss"></style>